package bookez.view.bean.backing;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import bookez.model.businessobject.User;
import bookez.model.exception.BookezException;
import bookez.model.exception.PasswordIncorrectException;
import bookez.model.exception.UserNotExistException;
import bookez.view.bean.NavigationResults;
import bookez.view.bean.UserBean;
import bookez.view.util.ProcessMessage;


@ManagedBean
@SessionScoped
public class LoginForm extends BaseBackingBean {

	
	public String login() {
		
		boolean validUsername = validateUsername();
		boolean validPassword = validatePassword();
		
		if( !validUsername || !validPassword ) { return NavigationResults.NONE; }
		
		try {
			
			
			User user = getUserBean().getService().login( this.username, this.password );
			
			if( user != null ) {
				getUserBean().setAuthenticated( true );
				getUserBean().setUsername( this.username );
				getUserBean().setPassword( this.password );
				return NavigationResults.LOGIN_SUCCESS;
			}//end if
			else {
				getUserBean().setAuthenticated( false );
				return NavigationResults.NONE;
			}
			
			
		}//end try
		catch ( UserNotExistException une ) {
			ProcessMessage.processError( "loginForm:username", UserBean.USER_NOT_EXITS, new Object[] { username } );
			return NavigationResults.NONE;
		}//end catch
		catch ( PasswordIncorrectException pie ) {
			ProcessMessage.processError( "loginForm:password", UserBean.PASSWORD_INCORRECT, null );
			return NavigationResults.NONE;
		}//end catch
		catch (BookezException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return NavigationResults.NONE;
		}//end catch
		
	}//end method login
	
	private boolean validateUsername() {	
		
		boolean result = true;

		if( username.isEmpty() ) {
			ProcessMessage.processError( "loginForm:username", UserBean.USERNAME_REQUIRED, null );
			result = false;
		}
		return result;
		
	}//end method validateUsername
	
	private boolean validatePassword() {		
		boolean result = true;
		if( password.isEmpty() ) {
			ProcessMessage.processError( "loginForm:password", UserBean.PASSWORD_REQUIRED, null );
			result = false;
		}
		return result;		
	}//end method validatePassword
	
	public String getUsername() { return this.username; }
	public void setUsername( String value ) { this.username = value; }
	
	public String getPassword() { return this.password; }
	public void setPassword( String value ) { this.password  = value; }
	
	protected UserBean getUserBean() { return this.userBean; }
	public void setUserBean( UserBean value ) { this.userBean = value; }
	
	
	@ManagedProperty ( value = "#{userBean}" )
	private UserBean userBean;
	
	private String username;
	private String password;
	
	private static final long serialVersionUID = 4856846723408967148L;
}//end class LoginForm
